#include "StdAfx.h"
#include "LinesEdit.h"
#include "ExtractShapeCenterOperator.h"
#include "LinesEditAddIn.h"

#include "HDiMineView.h"
#include "SelectionSet.h"
#include "SelectOperator.h"
#include "HDiMineModel.h"
#include "WorkPlaneManager.h"
#include "dmGeoData.h"
#include "dmMath.h"
#include "HPointArray.h"
#include "Geometry.h"
#include "tw_md.h"
#include "geoConvert.h"
#include "CAppSettings.h"
#include "BoundaryBuilder.h"
#include "dmCmnFunc.h"
#include "SelectionItem.h"
#include "polyline.h"
#include "DBConversion.h"
#include "dmMath.h"

CExtractShapeCenterOperator::CExtractShapeCenterOperator(HDiMineView* view,IDMAddIn *addin):CAddInBaseOperator(view,addin)
{
}

CExtractShapeCenterOperator::~CExtractShapeCenterOperator(void)
{
}
int CExtractShapeCenterOperator::Init()
{
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	PromptMessage(ID_STR_SELOBJ_RENSURE);
	return 1;
}
void CExtractShapeCenterOperator::OnExit()
{
}
int CExtractShapeCenterOperator::OnLButtonDown(dmEventInfo &hevent)
{
	m_ptNew = GetMouseWorldPos(hevent);;

	Relegate(new CSelectOperator(m_pView,this,&hevent,SEL_ALL));

	m_pView->Update();

	return DM_OP_OK;
}

int CExtractShapeCenterOperator::OnRButtonDown(dmEventInfo &hevent)
{
	CSelectionSet *pSel = m_pView->GetSelection();
	if (pSel->GetSize()<=0)
	{
		return DM_OP_OK;
	}
	CdmLayerBase *pToLayer = GetNewDataLayer(pSel->GetEntityAt(0));
	CdmEntityBase *pEntity = NULL;
	dmDPoint *pts = NULL;
	int npts = 0;
	dmDPoint newPnt;
	dmEntityArray tempArray;	
	for (unsigned int i=0;i<pSel->GetSize();i++)
	{
		pEntity = pSel->GetEntityAt(i);	
		dmDbPolyline *pPoly = pEntity->Polylized(0.1f);
	//	dmDbPolyline* pPoly=dmDbPolyline::SafeDownCast(pl);
		if (pPoly == NULL)			continue;	
		int n;
		dmDPoint *pts=NULL;
		pPoly->GetGraphData(pts,n);
		/*if(pts[0]!=pts[n-1])
		{				
	
			dmDbPolyline * pNewEn=pPoly->Clone();

			dmDPoint* pPtsPoly=new dmDPoint[n+1];
			memcpy(pPtsPoly,pts,n*sizeof(dmDPoint));
			pPtsPoly[n]=pts[0];
			pNewEn->SetGraphData(pPtsPoly,n+1);
			pPoly->Delete();
			pPoly=pNewEn;
			delete []pPtsPoly;
			twModelFunc::CalculateCenterorid(n,pts,newPnt);
		}

		newPnt = pPoly->GetCentriod();	*/

		twModelFunc::CalculateCenterorid(n,pts,newPnt);
		

		CdmEntityBase *pNewEnt = pToLayer->InsertPoint(newPnt);
		if (pNewEnt != NULL)
		{
			pNewEnt->Display();
			tempArray.Append(pNewEnt);
		}	
		//delete []pts;
		pPoly->Delete();
	}

	if(tempArray.Count())
	{
		AddInsertUndoItem(tempArray.Array(),tempArray.Count());
	}

	twModelFunc::Clear(tempArray);

	pSel->DeSelectAll();
	m_pView->Update();
	return DM_OP_OK;
}
